package com.guigu.qingcheng.controller;

import com.guigu.qingcheng.handler.SkuElasticSearchHandler;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @ClassName SearchController
 * @Description
 * @Author Simon
 * @Date 2020/8/20 10:42
 * @Version 1.0
 **/
@Controller
@Slf4j
@Api(tags = "SearchController")
public class SearchController {

    @Resource
    private SkuElasticSearchHandler skuES;

    @GetMapping("/search")
    @ApiOperation("测试查询")
    public String search(Model model, @RequestParam Map<String,String> map){
        if (map.get("pageNo") == null) {
            map.put("pageNo","1");
        }
        // 注意: map的设置顺序会影响前端的映射
        // 升序降序
        if (map.get("sortOrder") == null) { // 排序规则
            map.put("sortOrder","DESC");
        }
        if (map.get("sort") == null) { // 排序字段
            map.put("sort","");
        }
        Map search = skuES.searchSkuES(map);
        model.addAttribute("result", search);
        // url 处理
        StringBuffer url = new StringBuffer("/protal/search?");
        for (String key : map.keySet()){
                url.append("&"+key+"="+map.get(key));
        }
        int pageNo = Integer.parseInt(map.get("pageNo"));
        model.addAttribute("pageNo",pageNo);
        int endPage = (Integer) search.get("totalPages");
        int startPage = 1;
        if (endPage>5) {
            startPage = pageNo-2;
            if(startPage<1){
                startPage = 1;
            }
            endPage = startPage+4;
        }
        model.addAttribute("startPage", startPage);
        model.addAttribute("endPage", endPage);
        model.addAttribute("url",url);
        model.addAttribute("searchMap",map);
        return "search";
    }

    @GetMapping("test")
    @ResponseBody
    public String test() {
        return "aaa";
    }


}
